# Create your views here.

from lads.views import template, json
from home.models import get_figure_types_choices, get_career_choices, get_career_by_id, Image, Lad, NO_PHOTO_THUMBNAIL, ProxyAddress
from home.forms import AddLadForm, FilterLadsForm, AddProxyAddressForm
from lads.imageripper import ImageRipper
from lads.image import init_thumbnail, update_thumbnail, Thumbnail
import os
from lads.settings import MEDIA_ROOT, MEDIA_URL, STATIC_URL, CELERY_LOG
from django.db.models import Q
from django.forms.models import model_to_dict
import re
from lads.utils import slugify_ru as slugify, remove_extra_gaps
from django.db.models import Count
from localsettings import DOMAIN, MYAUTH_VK_ID, MYAUTH_FB_ID

_THUMBNAIL_SIZE = 260

@template
def photo_log( request ):
	with open( CELERY_LOG, 'r' ) as f:
		lines = f.readlines()
	return request, { 'template': "home/photo-log.html", 'out': { 'log': "\n".join( lines[ -50: ] ) } }

@template
def proxy( request ):
	out = {}
	if request.method == 'POST':
		f = AddProxyAddressForm( request.POST )
		if f.is_valid():
			f.save()
			out[ 'added_addr' ] = f.cleaned_data[ 'addr' ]
		else:
			out[ 'addr' ] = request.POST[ 'addr' ]
		out.update( form = f )
	
	out[ 'num_active_proxies' ] = ProxyAddress.objects.filter( is_active = True ).count()
	
	return request, { 'template': "home/proxy.html", 'out': out }

@json
def get_photos( request ):
	lad_id = request.REQUEST[ 'id' ]
	images = Image.objects.filter( lad__id = lad_id ).order_by( 'id' )
	result = []
	for im in images:
		result.append( os.path.join( MEDIA_URL, im.image ) )
	return request, result

@json
def delete_image( request ):
	image_id = request.REQUEST[ 'id' ]
	Image.objects.get( id = image_id ).delete()

	return request, { 'id': image_id }

@template
def unhandled_lad_profile( request ):	
	get = request.GET
	if 'next' in get:	
		lad = Lad.objects.get( id = get[ 'lad_id' ] )
		lad.handled = True
		lad.save()
	#lad = Lad.objects.filter( handled = False ).order_by( '-id' )[ 0 ]		
	lad = Lad.objects.annotate( image_count = Count( 'image' )	).filter( handled = False, image_count__gt = 0 ).order_by( '-id' )[ 0 ]
	images = Image.objects.filter( lad = lad )
	return request, { 'template': "home/unhandled-lad-profile.html", 'out': { 'lad': lad, 'images': images } }

@template
def lad_profile( request, slug ):
	lad = Lad.objects.get( slug = slug )
	images = Image.objects.filter( lad = lad )
	return request, { 'template': "home/lad-profile.html", 'out': { 'lad': lad, 'images': images } }

@template
def how_many( request ):
	track_id = request.GET[ 'track-id' ]
	count = Lad.objects.filter( track_id = track_id ).count()

	return request, { 'template': "home/how_many.html", 'out': { 'track_id': track_id, 'count': count } }

_NUM_LADS_ON_PAGE = 40

def _get_page_offset( req ):
	page = int( req[ 'page' ] ) if 'page' in req else 1
	return page, ( page - 1 ) * _NUM_LADS_ON_PAGE

def _get_lads_by_page( request_req, page ):
	p, offset = _get_page_offset( request_req )
	return Lad.objects.all().order_by( '-id' )[ offset : offset + _NUM_LADS_ON_PAGE ] # may be non-effective SQL	

@json
def viewer_lazy_load( request ):
	get = request.GET
	page = int( get[ 'page' ] ) if 'page' in get else 1
	return request, { 'result': _lads_for_json( _get_lads_by_page( request.GET, page ) ), 'page': page }

@template
def home( request ):
	return request,	{	
						'template': "home/index.html", 
						'out': 
						{ 
							'domain': DOMAIN, 
							'vk_id': MYAUTH_VK_ID, 
							'fb_id': MYAUTH_FB_ID,
							'figure_types_choices': get_figure_types_choices(), 
							'career_choices': get_career_choices() 
						}
					}

@template
def viewer( request ):	
	figure_types_choices = get_figure_types_choices()
	career_choices = get_career_choices()
	get = request.GET
	page = int( get[ 'page' ] ) if 'page' in get else 1
	lads = _get_lads_by_page( request.GET, page )

	out = { 'lads': lads, 'figure_types_choices': get_figure_types_choices(), 'career_choices': get_career_choices() }

	num_lads = Lad.objects.all().count()
	next_page_offset = page * _NUM_LADS_ON_PAGE

	if next_page_offset < num_lads:
		out.update( next_page = page + 1 )
	

	return request, { 'template': "home/viewer.html", 'out': out }


@json
def save_thumbnail( request ):

	# ! note: we have image_id in template. Use it.

	d = request.REQUEST
	image_id = int( d[ 'image_id' ] )
	image = Image.objects.select_related().get( id = image_id )	
	lad = image.lad
	x = int( d[ 'x' ] )
	y = int( d[ 'y' ] )
	size = int( d[ 'size' ] )

	src_image_path = os.path.join( MEDIA_ROOT, image.image )	
	thumb_name = 'lads/{0}'.format( update_thumbnail( src_image_path, x, y, size ) )

	lad.thumbnail = Thumbnail(	thumb_name, x, y, size )
	lad.save()
	return request, {}

def _q_by_name_surname( name_surname ):
	name_surname = remove_extra_gaps( name_surname )
	
	gap_pos = name_surname.find( ' ' )			
	
	if gap_pos != -1:				
		nsq = Q( name_surname__iexact = name_surname ) 
		name = name_surname[ : gap_pos ]
		surname = name_surname[ gap_pos + 1: ]
		nsq |= Q( name_surname__iexact = u"{0} {1}".format( name, surname ) )
		nsq |= Q( name_surname__iexact = u"{1} {0}".format( name, surname ) )
	else:
		nsq = Q( name_surname__icontains = name_surname ) 

	return nsq

@json
def filter_lads( request ):
	# returns list of lads
	get = request.GET
	f = FilterLadsForm( get )

	page, offset = _get_page_offset( get )

	result = []
	if f.is_valid():
		data = f.cleaned_data
		name_surname = data[ 'name_surname' ]
		career = data[ 'career' ]
		figure_type = data[ 'figure_type' ]
		age__lte = data[ 'age__lte' ]
		age__gte = data[ 'age__gte' ]

		q = Q()
		
		if name_surname != "":
			# replace 'continuous' gap
			nsq = _q_by_name_surname( name_surname )			
			q &= nsq

		if career != "":
			q &= Q( career = career ) 
			
		if figure_type != "":
			q &= Q( figure_type = figure_type )

		if age__lte != None:
			q &= Q( age__lte = age__lte )

		if age__gte != None:
			q &= Q( age__gte = age__gte )

		lads = Lad.objects.filter( q )[ offset: offset + _NUM_LADS_ON_PAGE ]

		for lad in lads:
			result.append( _get_lad_dict( lad ) )

	return request, { 'result': result, 'errors': f.errors, 'page': page }

def _get_lad_dict( lad ):
	return {
				'name_surname': lad.name_surname,
				'career': lad.get_career_display(),
				'id': lad.id,
				'thumbnail': lad.get_thumbnail_url(),
				'slug': lad.slug
			}

def _lads_for_json( lads ):
	result = []
	for lad in lads:
		result.append( _get_lad_dict( lad ) )
	return result

@json
def all_lads( request ):
	lads = Lad.objects.all().order_by( '-id' )[ : _NUM_LADS_ON_PAGE ]
	result = []
	for lad in lads:
		result.append( _get_lad_dict( lad ) )
	
	return request, { 'result': result }

@json
def add_lad( request ):
	f = AddLadForm( request.REQUEST )
	if f.is_valid():				
		name_surname = remove_extra_gaps( f.cleaned_data[ 'name_surname' ] )

		found_lads = Lad.objects.filter( _q_by_name_surname( name_surname ) )
		if len( found_lads ) > 0:
			return request, { 'result': "FOUND", 'lad': _get_lad_dict( found_lads[ 0 ] ) }

		slug = slugify( name_surname )
		f.instance.slug = slug
		f.save()
		
		f.instance.save()
		
		id2 = f.instance.id
		
		profile = {}
		profile[ 'name_surname' ] = f.cleaned_data[ 'name_surname' ]
		profile[ 'career' ] = get_career_by_id( f.cleaned_data[ 'career' ] )

		d = { 'profile': profile, 'id': id2, 'slug': slug }

		d.update( { 'result': "OK", 'url': STATIC_URL + NO_PHOTO_THUMBNAIL } )
		
		return request, d
	else:			
		return request, { 'result': "ERROR", 'errors': f.errors }
